package com.example.filters;

import com.alibaba.fastjson.JSON;
import com.example.common.entitys.AuthUserDetails;
import com.example.threadloacls.AuthUserDetailsThreadlocal;
import com.example.utils.TraceIdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TraceIdInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(TraceIdInterceptor.class);
    public static final String traceIdTag = "traceId";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("执行TraceIdInterceptor");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //先从param里取，没有的话从header里取，还没有的话再创建
        String traceId = request.getParameter(traceIdTag);
        if (!StringUtils.hasLength(traceId)){
            traceId = httpServletRequest.getHeader(traceIdTag);
        }
        if (!StringUtils.hasLength(traceId)){
            traceId = TraceIdUtils.getTraceId();
        }

        MDC.put(traceIdTag, traceId);

         return true;



    }
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        MDC.remove(traceIdTag);
    }
}
